package com.example.xmhds_1.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池配置
 */
@Configuration
@Slf4j
public class ThreadPoolConfig {

    @Bean(name = "heartbeatScheduler")
    public ScheduledExecutorService heartbeatScheduler() {
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(
                1,  // 核心线程数
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r);
                        thread.setName("heartbeat-thread-" + thread.getId());
                        thread.setDaemon(true);  // 设置为守护线程
                        return thread;
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy()  // 拒绝策略
        );

        // 添加监控
        executor.setRemoveOnCancelPolicy(true);
        executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);

        return executor;
    }
    // 可以添加线程池监控方法
    public void monitorThreadPool(ScheduledThreadPoolExecutor executor) {
        log.info("线程池状态:");
        log.info("核心线程数: {}", executor.getCorePoolSize());
        log.info("当前线程数: {}", executor.getPoolSize());
        log.info("队列任务数: {}", executor.getQueue().size());
        log.info("已完成任务数: {}", executor.getCompletedTaskCount());
    }
}